import Layout from 'layout'
import React, {Component} from 'react'
import Router from 'next/router'
import {observable, computed} from 'mobx'
import {observer, Provider, inject} from 'mobx-react'
import classNames from 'classnames'
import SimpleMDE from 'react-simplemde-editor'
import mdeStyle from 'react-simplemde-editor/dist/simplemde.min.css'
import {Menu, Dropdown, Button, Icon, Input, Tag, message} from 'antd'
import request from 'utils/request'
import pinyin from 'utils/pinyin'
import time from 'utils/time'
// import * as styles from 'styles/edit' 
import {inputGroup, rightPanel, editHeader} from 'styles/edit'

// 问题:
// Menu.Item的是非选择项需要返回ajacent divs的

class Store {
  @observable title
  @observable id
  @observable content
  @observable time
  @observable href
  @observable tag = []
  @observable tagList = []
  @observable isPublished
  @observable isUnsaved
  @observable isPanelOpen
  constructor(data){
    this.id = data.id
    this.title = data.title
    this.content = data.content
    this.time = data.time
    this.tag = data.tag
    this.tagList = []
    this.isPublished = data.isPublished
    this.href = data.href
    this.isPanelOpen = false
    this.isUnsaved = data.id ? false: true
  }
}

// 操作面板的输入Wrapper
function InputGroup({title, icon, customContent, children, value, onChange}) {
  return (
    <div className="input-group">
      <strong>{title}</strong>
      {!customContent&&!children ?
        <Input
          prefix={<Icon type={icon} style={{ color: 'rgba(0,0,0,.25)' }} />}
          value={value}
          onChange={(e)=>onChange(e.target.value)}
        /> :
        children
      }
      <style jsx>{inputGroup}</style>
    </div>
  )
}

// 操作面板的标签组
@inject('store', 'onFindTag', 'onAddTag', 'onAddTagToBlog') @observer
class TagGroup extends Component {
  constructor(){
    super()
    this.state = {value:''}
  }

  async handleMenuClick(e){
    if(e.key === 'add') {
      const _id = await this.props.onAddTag(this.state.value)
      this.props.onAddTagToBlog({id: _id, name: this.state.value})
    } else {
      await this.props.onAddTagToBlog({id:e.key})
    }
    this.setState({value: ''})
  }

  tagValueChange(e){
    const value = e.target.value
    this.setState({value})
    this.props.onFindTag(value)
  }
  
  render() {
    const store = this.props.store
    return (
      <Dropdown overlay={
        <Menu onClick={this.handleMenuClick.bind(this)}>
          <Menu.Item key="add">新增{this.state.value}...</Menu.Item>
          {store.tagList.map(tag =>
            <Menu.Item key={tag._id}>{tag.name}</Menu.Item>
          )}
        </Menu>
      }>
        <Input
          prefix={<Icon type='tags' style={{ color: 'rgba(0,0,0,.25)' }}/>}
          value={this.state.value}
          onChange={this.tagValueChange.bind(this)}
        />
      </Dropdown>
    )
  }
  
}

// 右侧操作面板
@inject('store','onRemoveTag') @observer
class RightPanel extends Component {
  render(){
    const store = this.props.store
    const props = this.props
    return (
      <div className="right-panel-mask"
        style={{right: store.isPanelOpen? 0 : '-100vw'}}
        onClick={() => store.isPanelOpen = false}
      >
        <div className="right-panel" style={{right: store.isPanelOpen? 0 : '-250px'}} onClick={(e)=> e.stopPropagation()}>
          <div>
            设置
            <Icon
              type="close"
              className="cp"
              style={{float:'right', marginTop: 5}}
              onClick={() => store.isPanelOpen = false}
            />
          </div>
          <InputGroup
            title='访问url'
            icon='link'
            onChange={(v)=> store.href=v}
            value={store.href}
          />
          <InputGroup
            title='发布日期'
            icon='calendar'
            onChange={(v)=>store.time=v}
            value={store.time}
          />
          <InputGroup title='标签' customContent={true}>
            <TagGroup/>
            <div className="tag-container">
              {store.tag.map((t,i)=>(
                <Tag
                key={t.name}
                closable
                onClose={()=>{props.onRemoveTag(t._id, i)}}
                >{t.name}</Tag>
              ))}
            </div>
          </InputGroup>
        </div>
        <style jsx global>{rightPanel}</style>
      </div>
    )
  }
}

// 发布/取消发布按钮
@inject('store','onDelete','onSave') @observer
class EditHeaderBtn extends Component {
 handleMenuClick(e) {
    if(e.key === 'publish' || e.key === 'update') this.props.onSave(true)
    else if(e.key === 'save' || e.key === 'withdraw') this.props.onSave()
    else this.props.onDelete()
  }

  render() {
    const store = this.props.store
    return (
      <Dropdown overlay={
        <Menu onClick={this.handleMenuClick.bind(this)}>
        {!store.isPublished && <Menu.Item key="save">保存</Menu.Item>}
        {store.isPublished ? 
          <Menu.Item key="update">更新</Menu.Item> :
          <Menu.Item key="publish">发布</Menu.Item>}
        {store.isPublished && <Menu.Item key="withdraw">撤回</Menu.Item>}        
        {!store.isUnsaved && <Menu.Item key="delete">删除</Menu.Item>}
      </Menu>
      }>
        <Button style={{marginLeft: 8}}>
          操作<Icon type="down"/>
        </Button>
      </Dropdown>
    )
  }
}

// editor头部条
@inject('store') @observer
class  EditHeader extends Component {
  render() {
    const store = this.props.store
    return (
      <div className='header-container'>
        <input value={store.title} onChange={e=>store.title=e.target.value}/>
        <style jsx>{editHeader}</style>
        <div className='btn-container'>
          <Icon type="setting"
            className="cp"
            style={{marginRight: 10}}
            onClick={()=>store.isPanelOpen = true}
          />
          <EditHeaderBtn/>
        </div>
      </div>
    )
  }
}

// editor编辑器
@inject('store') @observer
class Editor extends Component {
  render() {
    const store = this.props.store
    return (
      <div>
        <SimpleMDE
          onChange={(value)=>store.content = value}
          value={store.content}
          options={{status: false}}
        />
        <style jsx global>{mdeStyle}</style>
        <style jsx global>{`
          .CodeMirror-scroll,.CodeMirror {
            min-height: 80vh;
          }
        `}</style>
      </div>
    )
  }
}

@observer
export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = {didMount: false}
    this.store = new Store({
      title: props.title,
      content: props.content,
      id: props._id,
      time: time(props.time).join('/'),
      tag: props.tag||[],
      href: props.href,
      isPublished: props.isPublished
    })
    // 拼音你怎么又烂了..
    // console.log(pinyin.convertToPinyin('还是很', '-', true))
  }

 static async getInitialProps({query}) {
    if(!query.id) return {}
    return (await request('get', `blog/${query.id}`)).data
  }

  componentDidMount() {
    this.setState({
      didMount: true
    })
  }

  // 保存/新建/发布/更新
  async saveBlog(isPublish = false){
    const store = this.store
    const res = (await request(store.id?'put':'post', `blog/${store.id||''}`, {
      id: store.id,
      content: store.content,
      title: store.title,
      href: store.href,
      time: Date.parse(store.time),
      isPublished: isPublish
    })).data
    message.success(`(●ˇ∀ˇ●)${isPublish ? '发布' : '保存'}完毕!`)
    if(isPublish) store.isPublished = true
    if(!store.id) {
      const id = res._id
      store.id = id
      Router.replace(`/admin/edit?id=${id}`, `/admin/edit?id=${id}`, { shallow: true })
    }
  }

  async deleteBlog(){
    await request('delete', `blog/${this.store.id}`)
    Router.replace('/admin')
  }
  
  async addTag(name){
    if(!name) return
    const {data} = await request('post', 'tag', {name})
    return data._id
  }

  async addTagToBlog({id}) {
    if(this.store.tag.indexOf(id)>-1) return
    const {data} = (await request('post', `blog/tag/${this.store.id}`, {
      tagId: id,
    }))
    this.store.tag.push({_id: id, name: data.name})
  }

  // 移除tag
  async removeTag(id, i) {
    if(!id) return
    await request('delete', `blog/tag/${this.store.id}`, {
      tagId: id
    })
    this.store.tag.splice(i, 1)
  }

  // 查询tag 这里要如何优化
  async findTag(start) {
    if(!start) return
    this.store.tagList = (await request('get', `tag/${start}`)).data
  }

  render() {
    const props = this.props
    const state = this.state
    return (
      <Provider
        store={this.store}
        onAddTag={this.addTag.bind(this)}
        onAddTagToBlog={this.addTagToBlog.bind(this)}
        onRemoveTag={this.removeTag.bind(this)}
        onFindTag={this.findTag.bind(this)}
        onSave={this.saveBlog.bind(this)}
        onDelete={this.deleteBlog.bind(this)}
      >
      <Layout>
        <EditHeader/>
        { this.state.didMount ? <Editor/> : <p>loading..</p> }
        <RightPanel/>
      </Layout>
      </Provider>
    )

  }
}